package com.whfc.common.third.xhhb;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.whfc.common.util.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 星华环保API
 * @author: xugcheng
 * @version: 1.0
 * @date: 2021-11-30 18:14
 */
public class XhhbApi {

    private static final Logger logger = LoggerFactory.getLogger(XhhbApi.class);

    private static final String URL = "http://121.89.185.91:20100/openApi/realtime/data";

    private static final Integer SUCCESS = 1001;

    private static final Map<String, String> integerMap = new HashMap<>();
    private static final Map<String, String> doubleMap = new HashMap<>();

    static {
        integerMap.put("PM2.5", "pm25");
        integerMap.put("PM10", "pm10");
        integerMap.put("TSP", "tsp");

        doubleMap.put("Humidity", "envRh");
        doubleMap.put("WindDirection", "windDirection");
        doubleMap.put("WindSpeed", "windSpeed");
        doubleMap.put("Noise", "noise");
        doubleMap.put("Temperature", "envTemp");
        doubleMap.put("Pressure", "atmos");
    }

    public static String getEnvData(String sn) {

        Map<String, String> params = new HashMap<>();
        params.put("SN", sn);

        String response = HttpUtil.doPost(URL, params);
        JSONObject ret = JSON.parseObject(response);
        if (ret != null && SUCCESS.equals(ret.getInteger("code"))) {
            JSONObject content = ret.getJSONObject("content");
            JSONObject result = new JSONObject();
            JSONArray array = content.getJSONArray("realtimeData");
            if (array != null && array.size() > 0) {
                for (int i = 0; i < array.size(); i++) {
                    JSONObject item = array.getJSONObject(i);
                    String name = item.getString("name");
                    BigDecimal data = item.getBigDecimal("data");
                    if (data != null) {
                        if (integerMap.containsKey(name)) {
                            result.put(integerMap.get(name), data.intValue());
                        }
                        if (doubleMap.containsKey(name)) {
                            result.put(doubleMap.get(name), data.doubleValue());
                        }
                    }
                }
            }
            String dateTime = content.getString("dateTime");
            result.put("time", dateTime);
            result.put("deviceCode", sn);
            return result.toString();
        }
        return null;
    }

    public static void main(String[] args) {
        String sn = "53789272";
        String res = getEnvData(sn);
        System.out.println(res);
    }
}
